var markerClusterer = null;
var map = null;
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
var URL = "https://spreadsheets.google.com/feeds/cells/0AtA64x1W_YAfdHZzZzdOZkUybVdSYTlpeTREY1JJa3c/od6/public/basic?alt=json";

var columnTranslation = {A: 'lat', B: 'lon', C: 'url', D: 'title', E: 'thumb'};
var numCols = Object.keys(columnTranslation).length;
var initialCenterMap = {
    lat: 30,
    lon: 0,
    zoom: 1
};

google.load('maps', '3', {
    other_params: 'sensor=false'
});

var styles = [[{
    url: '../images/people35.png',
    height: 35,
    width: 35,
    anchor: [16, 0],
    textColor: '#ff00ff',
    textSize: 10
}, {
    url: '../images/people45.png',
    height: 45,
    width: 45,
    anchor: [24, 0],
    textColor: '#ff0000',
    textSize: 11
}, {
    url: '../images/people55.png',
    height: 55,
    width: 55,
    anchor: [32, 0],
    textColor: '#ffffff',
    textSize: 12
}], [{
    url: '../images/conv30.png',
    height: 27,
    width: 30,
    anchor: [3, 0],
    textColor: '#ff00ff',
    textSize: 10
}, {
    url: '../images/conv40.png',
    height: 36,
    width: 40,
    anchor: [6, 0],
    textColor: '#ff0000',
    textSize: 11
}, {
    url: '../images/conv50.png',
    width: 50,
    height: 45,
    anchor: [8, 0],
    textSize: 12
}], [{
    url: '../images/heart30.png',
    height: 26,
    width: 30,
    anchor: [4, 0],
    textColor: '#ff00ff',
    textSize: 10
}, {
    url: '../images/heart40.png',
    height: 35,
    width: 40,
    anchor: [8, 0],
    textColor: '#ff0000',
    textSize: 11
}, {
    url: '../images/heart50.png',
    width: 50,
    height: 44,
    anchor: [12, 0],
    textSize: 12
}]];

var infowindow = null;

function addMarker(markers, data) {
    var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));
    var latLng = new google.maps.LatLng(data.lat, data.lon);
    var marker = new google.maps.Marker({
        position: latLng,
        draggable: false,
        icon: markerImage,
        animation: google.maps.Animation.DROP,
        data: data
    });
    markers.push(marker);
    google.maps.event.addListener(marker, 'click', function(evt) {
        var content;
        if (marker.data.thumb !== undefined) {
            content = '<a href="' + marker.data.url + '"><img src="' + marker.data.thumb + '" width="100" align="left" border="0"/></a><a href="' + marker.data.url + '">' + marker.data.title + '</a>';
        } else {
            content = '<a href="' + marker.data.url + '">' + marker.data.title + '</a>';
        }
        infowindow.setContent(content);
        infowindow.open(map, marker);
    });
}

function refreshMap( dataMarks ) {
    if (markerClusterer)
        markerClusterer.clearMarkers();

    infowindow = new google.maps.InfoWindow({
        size: new google.maps.Size(50, 50)
    });

    var markers = [];

    for (var i = 0; i < dataMarks.length; ++i) {
        addMarker(markers, dataMarks[i]);
    }

    var zoom = -1;//parseInt(document.getElementById('zoom').value, 10);
    var size = -1;//parseInt(document.getElementById('size').value, 10);
    var style = -1;//parseInt(document.getElementById('style').value, 10);
    zoom = zoom == -1 ? null : zoom;
    size = size == -1 ? null : size;
    style = style == -1 ? null : style;

    markerClusterer = new MarkerClusterer(map, markers, {
        maxZoom: zoom,
        gridSize: size,
        styles: styles[style],
        zoomOnClick: false
    });
    google.maps.event.addListener(markerClusterer, 'clusterclick', function(mc) {
        //var markers = $.extend({}, mc.clusterIcon_.cluster_.markers_);
        var markers = $.extend({}, mc.a);
        mc.getMap().fitBounds(mc.getBounds());
        var zoom = mc.getMap().getZoom();
        var maxZoom = 15;
        if (zoom >= maxZoom) {
            // atingiu o limite
            var latLon = markers[0].getPosition();
            mc.getMap().setZoom(maxZoom);
            setTimeout(function() {
                var content = '<table width="350">';
                var numMarkers = Object.keys(markers).length;
                for(var i = 0; i < numMarkers; i++) {
                    if (markers[i].data.thumb !== undefined) {
                        content += '<tr><td><a href="' + markers[i].data.url + '"><img src="' + markers[i].data.thumb + '" width="100" border="0"/></a></td><td valign="top"><a href="' + markers[i].data.url + '">' + markers[i].data.title + '</a></td></tr>';
                    } else {
                        content += '<tr><td colspan="2" valign="top"><a href="' + markers[i].data.url + '">' + markers[i].data.title + '</a></td></tr>';
                    }
                }
                content += '</table>';
                console.log(latLon.lat());
                infowindow.setContent(content);
                infowindow.setPosition(latLon);
                infowindow.open(map);
            }, 300);
        }
    });
}

function initialize( dataMarks ) {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: initialCenterMap.zoom,
        center: new google.maps.LatLng(initialCenterMap.lat, initialCenterMap.lon),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    //var refresh = document.getElementById('refresh');
    //google.maps.event.addDomListener(refresh, 'click', refreshMap);

    refreshMap( dataMarks );
}

function parseSpreadsheetData( resultData ) {
    var dataMarks = [];
    var idx = -1;
    for (var i = 0; i < resultData.feed.entry.length; i++) {
        if (!(i % numCols)) dataMarks[++idx] = {};
        var cellName = resultData.feed.entry[i].title.$t;
        var cellValue = resultData.feed.entry[i].content.$t;
        dataMarks[idx][columnTranslation[cellName.substring(0, 1)]] = cellValue;
    }
    return dataMarks;
}

$(document).ready(function() {
    var dataMarks;
    $.ajax({url: URL, async: false}).done(function(result) {
        dataMarks = parseSpreadsheetData(result);
    });
    $("#demo").html(JSON.stringify(dataMarks));
    console.log(dataMarks);
    initialize(dataMarks);
});
